package com.keyue.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.keyue.common.constant.Constant;
import com.keyue.common.constant.ServerResult;
import com.keyue.common.exception.BusinessException;
import com.keyue.common.utils.PageUtils;
import com.keyue.common.utils.TransactionHelper;
import com.keyue.domain.dto.CarInfoDO;
import com.keyue.domain.dto.CarParamInfoDO;
import com.keyue.domain.vo.CarInfoQueryVO;
import com.keyue.domain.vo.CarInfoVO;
import com.keyue.domain.vo.CarParamInfoVO;
import com.keyue.domain.vo.ImageItemVO;
import com.keyue.mapper.CarInfoMapper;
import com.keyue.service.CarInfoService;
import com.keyue.service.CarParamInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 车辆信息(CarInfo)表服务实现类
 *
 * @author makejava
 * @since 2025-07-02 11:44:58
 */
@Slf4j
@Service
public class CarInfoServiceImpl extends ServiceImpl<CarInfoMapper, CarInfoDO> implements CarInfoService {

    @Resource
    private CarParamInfoService carParamInfoService;

    @Resource
    private TransactionHelper transactionHelper;

    /**
     * 通过ID查询单条数据
     * <p>
     * carInfoQueryVO 主键
     *
     * @return 实例对象
     */
    @Override
    public ServerResult queryById(CarInfoQueryVO carInfoQueryVO) {
        if (Objects.isNull(carInfoQueryVO.getId())) {
            return ServerResult.fail("id 不能为空");
        }
        CarInfoDO carInfoDO = getById(carInfoQueryVO.getId());
        if (Objects.isNull(carInfoDO)) {
            return ServerResult.success(null);
        }
        CarInfoVO carInfoVO = BeanUtil.copyProperties(carInfoDO, CarInfoVO.class);
        if (StringUtils.isNotBlank(carInfoDO.getImgItems())) {
            carInfoVO.setImageItemVOList(JSONArray.parseArray(carInfoDO.getImgItems(), ImageItemVO.class));
        }
        CarParamInfoDO paramInfoDO = carParamInfoService.getById(carInfoDO.getParamId());
        CarParamInfoVO carParamInfoVO = BeanUtil.copyProperties(paramInfoDO, CarParamInfoVO.class);
        if (StringUtils.isNotBlank(paramInfoDO.getInnerItems())) {
            carParamInfoVO.setInnerImageItems(JSONArray.parseArray(paramInfoDO.getInnerItems(), ImageItemVO.class));
        }
        if (StringUtils.isNotBlank(paramInfoDO.getOutItems())) {
            carParamInfoVO.setOutImageItems(JSONArray.parseArray(paramInfoDO.getOutItems(), ImageItemVO.class));
        }
        carInfoVO.setCarParamInfoVO(carParamInfoVO);

        return ServerResult.success(carInfoVO);
    }

    /**
     * 分页查询
     *
     * @param carInfoQueryVO 筛选条件
     * @return 查询结果
     */
    @Override
    public ServerResult listByPage(CarInfoQueryVO carInfoQueryVO) {

        LambdaQueryWrapper<CarInfoDO> queryWrapper = buildQueryWrapper(carInfoQueryVO);
        Page page = new Page<>(carInfoQueryVO.getPage(), carInfoQueryVO.getPageSize());
        IPage<CarInfoDO> iPage = page(page, queryWrapper);
        carInfoQueryVO.setTotal(Long.valueOf(iPage.getTotal()).intValue());
        List<CarInfoDO> carInfoDOS = iPage.getRecords();
        if (CollectionUtils.isEmpty(carInfoDOS)) {
            return ServerResult.success(PageUtils.getUnifiedEmptyPage(carInfoQueryVO));
        }
        List<CarInfoVO> carInfoVOS = carInfoDOS.stream().map(x -> {
            CarInfoVO carInfoVO = new CarInfoVO();
            BeanUtil.copyProperties(x, carInfoVO);
            if (StringUtils.isNotBlank(x.getImgItems())) {
                carInfoVO.setImageItemVOList(JSONArray.parseArray(x.getImgItems(), ImageItemVO.class));
            }
            return carInfoVO;
        }).collect(Collectors.toList());
        Page<CarInfoVO> carInfoVOPage = new Page<>();
        carInfoVOPage.setCurrent(page.getCurrent());
        carInfoVOPage.setTotal(page.getTotal());
        carInfoVOPage.setSize(page.getSize());
        carInfoVOPage.setPages(page.getPages());
        carInfoVOPage.setRecords(carInfoVOS);
        return ServerResult.success(PageUtils.getUnifiedPageReturn(carInfoVOPage));
    }

    /**
     * @param carInfoQueryVO
     * @return
     */
    private LambdaQueryWrapper<CarInfoDO> buildQueryWrapper(CarInfoQueryVO carInfoQueryVO) {
        LambdaQueryWrapper<CarInfoDO> queryWrapper = new LambdaQueryWrapper<CarInfoDO>()
                .eq(CarInfoDO::getEnableFlag, Constant.ENABLE_TEN)
                .like(StringUtils.isNotBlank(carInfoQueryVO.getName()), CarInfoDO::getName, carInfoQueryVO.getName())
                .eq(StringUtils.isNotBlank(carInfoQueryVO.getBrandCode()), CarInfoDO::getBrandCode, carInfoQueryVO.getBrandCode())
                .eq(StringUtils.isNotBlank(carInfoQueryVO.getCarTypeCode()), CarInfoDO::getCarTypeCode, carInfoQueryVO.getCarTypeCode())
                .eq(StringUtils.isNotBlank(carInfoQueryVO.getCityCode()), CarInfoDO::getCityCode, carInfoQueryVO.getCityCode())
                .orderByDesc(CarInfoDO::getId);
        return queryWrapper;
    }

    /**
     * 新增数据
     *
     * @param carInfoVO 实例对象
     * @return 实例对象
     */
    @Override
    public ServerResult add(CarInfoVO carInfoVO) {

        if (Objects.nonNull(carInfoVO.getId())) {
            carInfoVO.setId(null);
        }
        CarParamInfoVO paramInfoVO = carInfoVO.getCarParamInfoVO();

        if (Objects.isNull(paramInfoVO)) {
            throw new BusinessException("车辆参数不能为空！");
        }

        if (Objects.nonNull(paramInfoVO.getId())) {
            paramInfoVO.setId(null);
        }
        CarParamInfoDO paramInfoDO = BeanUtil.copyProperties(paramInfoVO, CarParamInfoDO.class);
        if (CollectionUtils.isNotEmpty(paramInfoVO.getOutImageItems())) {
            paramInfoDO.setOutItems(JSONArray.toJSONString(paramInfoVO.getOutImageItems()));
        }
        if (CollectionUtils.isNotEmpty(paramInfoVO.getInnerImageItems())) {
            paramInfoDO.setInnerItems(JSONArray.toJSONString(paramInfoVO.getInnerImageItems()));
        }
        CarInfoDO carInfoDo = BeanUtil.copyProperties(carInfoVO, CarInfoDO.class);

        if (CollectionUtils.isNotEmpty(carInfoVO.getImageItemVOList())) {
            carInfoDo.setImgItems(JSONArray.toJSONString(carInfoVO.getImageItemVOList()));
        }

        transactionHelper.run(() -> {
            carParamInfoService.save(paramInfoDO);

            carInfoDo.setParamId(paramInfoDO.getId());
            save(carInfoDo);
        });

        return ServerResult.success();
    }

    /**
     * 修改数据
     *
     * @param carInfoVO 实例对象
     * @return 实例对象
     */
    @Override
    public ServerResult edit(CarInfoVO carInfoVO) {
        if (Objects.isNull(carInfoVO.getId())) {
            throw new BusinessException("车辆信息id不能为空！");
        }
        CarParamInfoVO paramInfoVO = carInfoVO.getCarParamInfoVO();

        if (Objects.isNull(paramInfoVO) || Objects.isNull(paramInfoVO.getId())) {
            throw new BusinessException("车辆参数或者id不能为空！");
        }

        CarParamInfoDO paramInfoDO = BeanUtil.copyProperties(paramInfoVO, CarParamInfoDO.class);
        if (CollectionUtils.isNotEmpty(paramInfoVO.getOutImageItems())) {
            paramInfoDO.setOutItems(JSONArray.toJSONString(paramInfoVO.getOutImageItems()));
        }
        if (CollectionUtils.isNotEmpty(paramInfoVO.getInnerImageItems())) {
            paramInfoDO.setInnerItems(JSONArray.toJSONString(paramInfoVO.getInnerImageItems()));
        }
        CarInfoDO carInfoDo = BeanUtil.copyProperties(carInfoVO, CarInfoDO.class);

        if (CollectionUtils.isNotEmpty(carInfoVO.getImageItemVOList())) {
            carInfoDo.setImgItems(JSONArray.toJSONString(carInfoVO.getImageItemVOList()));
        }

        transactionHelper.run(() -> {
            carParamInfoService.updateById(paramInfoDO);

            carInfoDo.setParamId(paramInfoDO.getId());
            updateById(carInfoDo);
        });


        return ServerResult.success();
    }

    /**
     * 通过主键删除数据
     *
     * @param carInfoQueryVO 筛选条件
     * @return 是否成功
     */
    @Override
    public ServerResult deleteById(CarInfoQueryVO carInfoQueryVO) {
        List<Long> ids = carInfoQueryVO.getIds();
        if (CollectionUtils.isEmpty(ids)) {
            return ServerResult.fail("ids 参数不能为空");
        }
        List<CarInfoDO> carInfoList = listByIds(ids);
        if (CollectionUtils.isEmpty(carInfoList)) {
            return ServerResult.success();
        }
        Set<Long> paramIds = carInfoList.stream().map(CarInfoDO::getParamId).collect(Collectors.toSet());
        LambdaUpdateWrapper<CarInfoDO> carInfoDOLambdaUpdateWrapper = new LambdaUpdateWrapper<CarInfoDO>()
                .in(CarInfoDO::getId, ids)
                .set(CarInfoDO::getEnableFlag, Constant.UNABLE_TWENTY);
        LambdaUpdateWrapper<CarParamInfoDO> carParamInfoDOLambdaUpdateWrapper = new LambdaUpdateWrapper<CarParamInfoDO>()
                .in(CarParamInfoDO::getId, paramIds)
                .set(CarParamInfoDO::getEnableFlag, Constant.UNABLE_TWENTY);

        transactionHelper.run(() -> {
            carParamInfoService.update(carParamInfoDOLambdaUpdateWrapper);

            update(carInfoDOLambdaUpdateWrapper);
        });
        return ServerResult.success();
    }
}
